<?php
declare(strict_types=1);

namespace app\service;

use app\model\{Order, MessageTemplateConfig, MessageRecord};
use think\facade\Log;

class NotificationService
{
    /**
     * 发送订单状态变更通知
     */
    public function sendOrderStatusNotification($order, $status)
    {
        try {
            // 获取消息模板
            $template = MessageTemplateConfig::where([
                'merchant_id' => $order->merchant_id,
                'message_setting_id' => $this->getMessageSettingId($status)
            ])->find();
            
            if (!$template) {
                return;
            }
            
            // 准备模板数据
            $data = [
                'order_no' => $order->order_no,
                'status' => $this->getStatusText($status),
                'time' => date('Y-m-d H:i:s'),
                'courier_name' => $order->courier_name ?? '',
                'courier_phone' => $order->courier_phone ?? '',
                'refund_amount' => $order->refund_amount ?? 0,
            ];
            
            // 记录发送结果
            $record = [
                'merchant_id' => $order->merchant_id,
                'user_id' => $order->user_id,
                'message_type' => $template->message_type,
                'message_template_id' => $template->id,
                'business_type' => 1, // 快递订单
                'business_id' => $order->id,
                'content' => json_encode($data, JSON_UNESCAPED_UNICODE),
                'create_time' => date('Y-m-d H:i:s')
            ];
            
            // 发送微信小程序通知
            if ($template->message_type == 1) {
                $success = $this->sendWxappNotification($order, $template, $data);
            }
            // 发送公众号通知
            else if ($template->message_type == 2) {
                $success = $this->sendMpNotification($order, $template, $data);
            }
            // 发送短信通知
            else if ($template->message_type == 3) {
                $success = $this->sendSmsNotification($order, $template, $data);
            }
            
            // 更新发送状态
            $record['status'] = $success ? 1 : 2;
            MessageRecord::create($record);
            
        } catch (\Exception $e) {
            Log::error('发送订单状态变更通知失败: ' . $e->getMessage());
            // 记录失败日志
            MessageRecord::create([
                'merchant_id' => $order->merchant_id,
                'user_id' => $order->user_id,
                'message_type' => $template->message_type ?? 0,
                'message_template_id' => $template->id ?? 0,
                'business_type' => 1,
                'business_id' => $order->id,
                'content' => $e->getMessage(),
                'status' => 2,
                'create_time' => date('Y-m-d H:i:s')
            ]);
        }
    }
    
    /**
     * 发送微信小程序通知
     */
    protected function sendWxappNotification($order, $template, $data)
    {
        $wechatService = new WechatService($order->merchant_id);
        return $wechatService->sendSubscribeMessage([
            'touser' => $order->user->openid,
            'template_id' => $template->template_id,
            'page' => 'pages/order/detail?id=' . $order->id,
            'data' => $this->formatTemplateData($template->template_content, $data)
        ]);
    }
    
    /**
     * 发送公众号通知
     */
    protected function sendMpNotification($order, $template, $data)
    {
        $wechatService = new WechatService($order->merchant_id);
        return $wechatService->sendTemplateMessage([
            'touser' => $order->user->mp_openid,
            'template_id' => $template->template_id,
            'url' => 'pages/order/detail?id=' . $order->id,
            'data' => $this->formatTemplateData($template->template_content, $data)
        ]);
    }
    
    /**
     * 发送短信通知
     */
    protected function sendSmsNotification($order, $template, $data)
    {
        $smsService = new SmsService($order->merchant_id);
        return $smsService->send(
            $order->user->mobile,
            $template->template_id,
            $this->formatTemplateData($template->template_content, $data)
        );
    }
    
    /**
     * 获取消息设置ID
     */
    protected function getMessageSettingId($status)
    {
        $map = [
            '200' => 1, // 已出单
            '201' => 2, // 出单失败
            '10' => 3,  // 已取件
            '13' => 4,  // 已签收
            '99' => 5,  // 订单取消
        ];
        return $map[$status] ?? 0;
    }
    
    /**
     * 获取状态文本
     */
    protected function getStatusText($status)
    {
        $map = [
            '200' => '已出单',
            '201' => '出单失败',
            '10' => '已取件',
            '13' => '已签收',
            '99' => '已取消',
        ];
        return $map[$status] ?? '';
    }
    
    /**
     * 格式化模板数据
     */
    protected function formatTemplateData($template, $data)
    {
        $result = [];
        
        // 解析模板变量
        preg_match_all('/\{\{(.*?)\}\}/', $template, $matches);
        
        if (!empty($matches[1])) {
            foreach ($matches[1] as $key) {
                $key = trim($key);
                if (isset($data[$key])) {
                    $result[$key] = [
                        'value' => $data[$key],
                        'color' => '#173177'
                    ];
                }
            }
        }
        
        return $result;
    }
} 